package com.service;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.bo.ArticleInfo;
import com.common.JPAUtil;
import com.entity.Article;
import com.entity.Content;
import com.entity.User;
import com.repository.ArticleRepository;
import com.repository.ContentRepository;
import com.repository.UserRepository;
import com.vo.PageBean;

@Service
@Transactional
public class IUserServiceImpl implements IUserService {

    @Autowired
    UserRepository userRep;

    @Autowired
    ArticleRepository articleRep;

    @Autowired
    ContentRepository contentRep;

    @Override
    public User insertUser(User user) {
        return userRep.save(user);
    }

    @Transactional(rollbackFor=Exception.class)
    @Override
    public ArticleInfo insertArtice(ArticleInfo article) {
        Date date = new Date();

        Article tmpArticle = article.getArticle();
        Content tmpContent = article.getContent();
        tmpArticle.setCreateTime(date);
        tmpArticle = articleRep.save(tmpArticle);

        tmpContent.setArticleId(tmpArticle.getId());
        tmpContent.setCreateTime(date);
        tmpContent = contentRep.save(tmpContent);

        article.setArticle(tmpArticle);
        article.setContent(tmpContent);

        return article;
    }

    private String getSimpleContnet(String content) {
        if (content.length() > 100) {
            return content.substring(0, 100) + "...";
        }
        return content + "...";
    }

    @Override
    public PageBean<Article> find(int pageIndex, int pageSize) {
        PageBean<Article> page = PageBean.newInstance();
        long count = articleRep.count();
        Pageable request = JPAUtil.getPageRequest(pageIndex, pageSize, count, JPAUtil.getDescSort("createTime"), page);
        page.setPageInfos(articleRep.findAll(request).getContent());
        return page;
    }

}
